/*****************************************************************************
*
*  PROJECT:     SlipStream
*               (Loader Class)
*  LICENSE:     GNU General Public License v3 - http://www.gnu.org/licenses/gpl.html

*  DEVELOPERS:  Philip Farquharson 	<B00137077@studentmail.uws.ac.uk>
*				John Gray 			<B00145524@studentmail.uws.ac.uk>		
*				Zohaib Bhatti		<B00104280@studentmail.uws.ac.uk>
*				Euan Hislop 		<B00138636@studentmail.uws.ac.uk>
*
*****************************************************************************/
#include "CLoader.h"

template<> CLoader * CSingleton< CLoader >::m_pSingleton = NULL;

CLoader::CLoader ( HDC hDC )
{
	m_texBackground = CTextureManager::GetSingletonPtr()->LoadTexture("textures/loading.png");
	m_hDC = hDC;
	m_iCurrentProgress = 0;
	m_iDesiredProgress = 0;
	m_bFading = false;
	m_fAlphaOffset = 0;
	Render();
}

void CLoader::Render ( void )
{
	if ( m_iCurrentProgress < 100 )
		glClear(GL_COLOR_BUFFER_BIT);

	glLoadIdentity();
	glDisable(GL_TEXTURE_2D);
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_LIGHTING);
	glEnable (GL_BLEND); 
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	
	glEnable(GL_TEXTURE_2D);
	glTranslatef(0.0, 0.0, -1.0f);
	
	Sleep(25);
	// draw background image
	glColor4f(1.0f, 1.0f, 1.0f, 0.7f + m_fAlphaOffset);
	m_texBackground->BindTexture();
	glBegin(GL_QUADS);
		glTexCoord2f(0.0f, 0.0f);
		glVertex2f(-0.85f, 0.6f);

		glTexCoord2f(0.0f, 1.0f);
		glVertex2f(-0.85f, -0.6f);
		
		glTexCoord2f(1.0f, 1.0f);
		glVertex2f(0.85f, -0.6f);
		
		glTexCoord2f(1.0f, 0.0f);
		glVertex2f(0.85f, 0.6f);
	glEnd();

	glDisable(GL_TEXTURE_2D);
	// draw progress bar background
	glColor4f(1.0f, 1.0f, 1.0f, 0.7f + m_fAlphaOffset);
	glBegin(GL_QUADS);
		glVertex2f(-0.35, -0.495);
		glVertex2f(-0.35, -0.55);
		glVertex2f(-0.75, -0.55);
		glVertex2f(-0.75, -0.495);
	glEnd();
	
	// progress smoothing
	if ( m_iDesiredProgress > m_iCurrentProgress )
		m_iCurrentProgress++;
	else if ( m_iDesiredProgress < m_iCurrentProgress )
		m_iCurrentProgress--;

	// draw progress
	float r, g = 0.0f;
	if ( m_iCurrentProgress <= 30 )
		r = 1.0f;
	else if ( m_iCurrentProgress > 30 && m_iCurrentProgress < 80 )
	{
		r = 1.0f;
		g = 1.0f;
	}
	else if ( m_iCurrentProgress >=80 )
	{
		r = 0.0f;
		g = 1.0f;
	}

	glColor4f(r, g, 0.0f, 0.7f + m_fAlphaOffset);
	glBegin(GL_QUADS);
		float x =  0.004 * m_iCurrentProgress;

		glVertex2f(-0.75, -0.495);
		glVertex2f(-0.75, -0.55);
		glVertex2f(-0.75+x, -0.55);
		glVertex2f(-0.75+x, -0.495);
	glEnd();
	

	if ( m_iCurrentProgress < 100 )
		SwapBuffers(m_hDC);

	glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
	glDisable(GL_BLEND);
	glDisable(GL_DEPTH_TEST);

	if ( m_iCurrentProgress != m_iDesiredProgress )
		Render();
}